package com.sealer;

/**
 * Created by sealer on 17-5-23.
 */
public class ReverseIn3Steps {
    /**
     * 三步反转法反转字符串
     * @param s
     * @param from 起点 包含
     * @param to   终点 不包含
     */
    public static void reverseString(char[] s, int from, int to) {
        while (from < to) {
            char c = s[from];
            s[from++] = s[to - 1];
            s[(to--) - 1] = c;
        }
    }

    /**
     * 三步反转法反转字符串
     * @param s
     * @param m
     * @return
     */
    public static String reverseRotateString(String s, int m) {
        char[] chars = s.toCharArray();
        reverseString(chars, 0, m);
        reverseString(chars, m, s.length());
        reverseString(chars, 0, s.length());
        return new String(chars);
    }


    /**
     * 三步反转法反转句子
     * @param strs 以空白符分隔的句子 空格 制表符tab
     * @param from 起点 包含
     * @param to 终点 不包含
     */
    public static void reverseSentence(String[] strs, int from, int to) {
        while(from < to) {
            String s = strs[from];
            strs[from++] = strs[to - 1];
            strs[(to--) - 1] = s;
        }
    }

    /**
     * 三步反转法反转句子
     * @param s
     * @param m
     * @return
     */
    public static String reverseRotateSentence(String s, int m) {
        String[] strs = s.split("\\s+");
        int length = strs.length;
        m = m % length;
        reverseSentence(strs, 0, m);
        reverseSentence(strs, m, length);
        reverseSentence(strs, 0, length);
        return String.join(" ", strs);
    }



    public static void main(String[] args) {
        System.out.println(reverseRotateString("hello sealer world!", 6));

        String s = "1234567890";
        s = reverseRotateString(s, 4);
        System.out.println(s);

        String ss = "I am a  student.";
        ss = reverseRotateSentence(ss, 2);
        System.out.println(ss);
    }
}
